package com.zyx.enhancement.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.zyx.enhancement.service.WeatherInfoService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.zyx.enhancement.common.HttpClientHelper.getDataOnHttp;

@Slf4j
@Service("weatherInfoService")
public class WeatherInfoServiceImpl implements WeatherInfoService {

    // 天气预报接口地址
    @Value("${content-enhancement.weather.api.url}")
    private String URL;

    // 天气预报接口密钥
    @Value("${content-enhancement.weather.api.key}")
    private String KEY;

    @Override
    public JSONObject queryWeather(String cityCode) {
        JSONObject result = null;
        // 参数列表
        Map<String, String> params = Map.of("key", KEY, "city", cityCode, "extensions", "base");

        // 请求结果
        JSONObject data = getDataOnHttp(URL, params);
        if (data == null) {
            log.error("【天气预报】接口返回 - NULL - ！");
            return result;
        }

        String status = data.getString("status");

        if(status.equals("1") && data.getString("infocode").equals("10000")) {
            int count = data.getIntValue("count");
            if (count > 0) {
                result = data.getJSONArray("lives").getJSONObject(0);
                log.info("【天气预报】接口返回RAW:{}", result);
                // result = weather.getString("weather");
                return result;
            } else {
                log.warn("【天气预报】接口返回 - 无数据 - ！");
            }

        }else{
            log.error("【天气预报】接口报错:[{}] Code[{}]- {}", status, data.getString("infocode"), data.getString("info"));
        }
        return result;
    }

}
